﻿Imports System
Imports System.Collections.Generic

Imports System.ComponentModel
Imports Microsoft.ConfigurationManagement
Imports Microsoft.ConfigurationManagement.ManagementProvider
Imports Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine



Module Module1

    Sub Main()
        QueryPackages(Connect)

    End Sub
    Public Function Connect() As WqlConnectionManager
        Dim strSiteServer As String = "server.domain.local"
        Dim strUserName As String = "domain\smsadmin"
        Dim strPassword As String = "password"
        Try
            Dim namedValues As SmsNamedValuesDictionary = New SmsNamedValuesDictionary()
            Dim connection As WqlConnectionManager = New WqlConnectionManager(namedValues)

            If System.Net.Dns.GetHostName().ToUpper() = strSiteServer.ToUpper() Then
                ' Connect to local computer.
                connection.Connect(strSiteServer)
            Else
                ' Connect to remote computer.
                connection.Connect(strSiteServer, strUserName, strPassword)
            End If

            Return connection
        Catch e As SmsException
            Console.WriteLine("Failed to Connect. Error: " + e.Message)
            Return Nothing
        Catch e As UnauthorizedAccessException
            Console.WriteLine("Failed to authenticate. Error:" + e.Message)
            Return Nothing
        End Try
    End Function


    Public Sub QueryPackages(ByVal connection As WqlConnectionManager)
        Try
            Dim query As IResultObject = connection.QueryProcessor.ExecuteQuery("SELECT * FROM SMS_R_System")
            Dim o As IResultObject
            For Each o In query
                Console.WriteLine(o("Name").StringValue)
                o.Dispose()
            Next
            Console.WriteLine("Press any key too continue...")
            Console.ReadLine()
        Catch ex As SmsException
            Console.WriteLine("Failed to query packages: " + ex.Message)
            Throw
        End Try
    End Sub
End Module
